<?
require_once(dirname(__FILE__) . '/../../classes/report_interface.inc.php');

abstract class LoggerModuleSourcesSearchReportBaseClass 
{
    protected $database;

    public function __construct(LoggerDatabase $database) 
    {
        $this->database = $database;
    }

    protected function GetQueriesData($date1, $date2, $engine, $start, $count)
    {
        $date1 = '\'' . mysql_escape_string($date1) . '\'';
        $date2 = '\'' . mysql_escape_string($date2) . '\'';

        $engineWhere = '';
        if ($engine !== false)
        {
            $engineWhere = '`s`.`engine`=\'' . mysql_escape_string($engine) . '\' AND ';
        }

        $SelectSQL = 'SELECT `text` AS `text`, `t`.`string` AS `textStr`, SUM(`summ`) AS `summ` FROM (';
        $SelectSQL .= 'SELECT `s`.`text`, SUM(`s`.`count`) AS `summ` ';
        $SelectSQL .= 'FROM `[PREF]module_sources_search_archive` `s` ';
        $SelectSQL .= 'WHERE '.$engineWhere.'`s`.`date`>='.$date1.' AND `s`.`date`<='.$date2.' ';
        $SelectSQL .= 'GROUP BY `s`.`text` ';

        $SelectSQL .= 'UNION ALL ';

        $SelectSQL .= 'SELECT `s`.`text`, COUNT(*) AS `summ` ';
        $SelectSQL .= 'FROM `[PREF]module_sources_search` `s` ';
        $SelectSQL .= 'WHERE '.$engineWhere.'`s`.`date`>='.$date1.' AND `s`.`date`<='.$date2.' ';
        $SelectSQL .= 'GROUP BY `s`.`text` ';

        $SelectSQL .= ') AS `__temp_query` ';
        $SelectSQL .= 'LEFT JOIN `[PREF]module_sources_strings` `t` ON `t`.`id`=`__temp_query`.`text` ';
        $SelectSQL .= 'GROUP BY `__temp_query`.`text` ';
        $SelectSQL .= 'ORDER BY `summ` DESC, `textStr` ';
        $SelectSQL .= 'LIMIT '.$start.','.$count;

        $data = array();
        $result = $this->database->Query($SelectSQL);
        if (!$result)
             trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);
        while ($row = $this->database->FetchAssoc($result))
        {
            $data[] = $row;
        }
        $this->database->FreeResult($result);
        return $data;
    }

    protected function GetEnginesData($date1, $date2)
    {
        $date1 = '\'' . mysql_escape_string($date1) . '\'';
        $date2 = '\'' . mysql_escape_string($date2) . '\'';

        $SelectSQL = 'SELECT `engine`, SUM(`summ`) AS `summ` FROM (';

        $SelectSQL .= 'SELECT `s`.`engine`, SUM(`s`.`count`) AS `summ` ';
        $SelectSQL .= 'FROM `[PREF]module_sources_search_archive` `s` ';
        $SelectSQL .= 'WHERE `s`.`date`>='.$date1.' AND `s`.`date`<='.$date2.' ';
        $SelectSQL .= 'GROUP BY `s`.`engine` ';

        $SelectSQL .= 'UNION ALL ';

        $SelectSQL .= 'SELECT `s`.`engine`, COUNT(*) AS `summ` ';
        $SelectSQL .= 'FROM `[PREF]module_sources_search` `s` ';
        $SelectSQL .= 'WHERE `s`.`date`>='.$date1.' AND `s`.`date`<='.$date2.' ';
        $SelectSQL .= 'GROUP BY `s`.`engine` ';

        $SelectSQL .= ') AS `__temp_query` ';
        $SelectSQL .= 'GROUP BY `engine` ';
        $SelectSQL .= 'ORDER BY `summ` DESC, `engine`';

        $data = array();
        $result = $this->database->Query($SelectSQL);
        if (!$result)
             trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);
        while ($row = $this->database->FetchAssoc($result))
        {
            $data[] = $row;
        }
        $this->database->FreeResult($result);
        return $data;
    }

    protected function GetEnginesByQueryData($date1, $date2, $text)
    {
        $date1 = '\'' . mysql_escape_string($date1) . '\'';
        $date2 = '\'' . mysql_escape_string($date2) . '\'';

        $textWhere = '';
        if ($text !== false)
        {
            $textWhere = '`s`.`text`=' . intval($text) . ' AND ';
        }

        $SelectSQL = 'SELECT `engine`, `page`, SUM(`summ`) AS `summ` FROM (';
        $SelectSQL .= 'SELECT `s`.`engine`, `s`.`page`, SUM(`s`.`count`) AS `summ` ';
        $SelectSQL .= 'FROM `[PREF]module_sources_search_archive` `s` ';
        $SelectSQL .= 'WHERE '.$textWhere.'`s`.`date`>='.$date1.' AND `s`.`date`<='.$date2.' ';
        $SelectSQL .= 'GROUP BY `s`.`text`, `s`.`page` ';

        $SelectSQL .= 'UNION ALL ';

        $SelectSQL .= 'SELECT `s`.`engine`, `s`.`page`, COUNT(*) AS `summ` ';
        $SelectSQL .= 'FROM `[PREF]module_sources_search` `s` ';
        $SelectSQL .= 'WHERE '.$textWhere.'`s`.`date`>='.$date1.' AND `s`.`date`<='.$date2.' ';
        $SelectSQL .= 'GROUP BY `s`.`text`, `s`.`page` ';

        $SelectSQL .= ') AS `__temp_query` ';
        $SelectSQL .= 'GROUP BY `engine`, `page` ';
        $SelectSQL .= 'ORDER BY `page`, `summ` DESC';

        $data = array();
        $result = $this->database->Query($SelectSQL);
        if (!$result)
             trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);
        while ($row = $this->database->FetchAssoc($result))
        {
            $data[] = $row;
        }
        $this->database->FreeResult($result);
        return $data;
    }
}

class LoggerModuleSourcesEnginesReport extends LoggerModuleSourcesSearchReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'Переходы с поисковиков');
        $root->appendChild($name);

        $data = $this->GetEnginesData($date1, $date2);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);

        foreach($data as $row)
        {
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('engine', $row['engine']);
            $dataRow->setAttribute('summ', $row['summ']);
        }

        $xsl = dirname(__FILE__) . '/templates/engines.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}

class LoggerModuleSourcesQueriesReport extends LoggerModuleSourcesSearchReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $limit_start = 0;
        $limit_count = 100;

        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'Поисковые запросы');
        $root->appendChild($name);

        $data = $this->GetQueriesData($date1, $date2, false, $limit_start, $limit_count);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);

        foreach($data as $row)
        {
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('textId', $row['text']);
            $dataRow->setAttribute('textStr', $row['textStr']);
            $dataRow->setAttribute('summ', $row['summ']);
        }

        if (count($data) == $limit_count)
        {
            $dataMore = $xml->createElement('report_data_more');
            $dataMore->setAttribute('start', $limit_count);
            $dataMore->setAttribute('count', $limit_count);
            if ($engine)
                $dataMore->setAttribute('engine', $engine);
            $root->appendChild($dataMore);
        }

        $xsl = dirname(__FILE__) . '/templates/queries.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}


class LoggerModuleSourcesQueriesMoreReport extends LoggerModuleSourcesSearchReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        if (!is_array($params) || !isset($params['start']))
            return false;

        $limit_start = intval($params['start']);
        $limit_count = 100;

        if (isset($params['count']))
            $limit_count = intval($params['count']);

        $xml = $root->ownerDocument;

        $data = $this->GetQueriesData($date1, $date2, false, $limit_start, $limit_count);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);

        foreach($data as $row)
        {
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('textId', $row['text']);
            $dataRow->setAttribute('textStr', $row['textStr']);
            $dataRow->setAttribute('summ', $row['summ']);
        }

        $xsl = dirname(__FILE__) . '/templates/queries_more.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}


class LoggerModuleSourcesQueriesByEngineReport extends LoggerModuleSourcesSearchReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $limit_start = 0;
        $limit_count = 100;

        $engine = false;
        if (is_array($params) && isset($params['engine']) && $params['engine'])
        {
            $engine = $params['engine'];
        }

        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'Поисковые запросы ' . $engine);
        $root->appendChild($name);

        $data = $this->GetQueriesData($date1, $date2, $engine, $limit_start, $limit_count);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);

        foreach($data as $row)
        {
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('engine', $engine);
            $dataRow->setAttribute('textId', $row['text']);
            $dataRow->setAttribute('textStr', $row['textStr']);
            $dataRow->setAttribute('summ', $row['summ']);
        }

        if (count($data) == $limit_count)
        {
            $dataMore = $xml->createElement('report_data_more');
            $dataMore->setAttribute('start', $limit_count);
            $dataMore->setAttribute('count', $limit_count);
            if ($engine)
                $dataMore->setAttribute('engine', $engine);
            $root->appendChild($dataMore);
        }

        $xsl = dirname(__FILE__) . '/templates/queries_by_engine.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}


class LoggerModuleSourcesQueriesByEngineMoreReport extends LoggerModuleSourcesSearchReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        if (!is_array($params) || !isset($params['start']))
            return false;

        $limit_start = intval($params['start']);
        $limit_count = 100;

        if (isset($params['count']))
            $limit_count = intval($params['count']);

        $engine = false;
        if (isset($params['engine']) && $params['engine'])
        {
            $engine = $params['engine'];
        }

        $xml = $root->ownerDocument;

        $data = $this->GetQueriesData($date1, $date2, $engine, $limit_start, $limit_count);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);

        foreach($data as $row)
        {
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('textId', $row['text']);
            $dataRow->setAttribute('textStr', $row['textStr']);
            $dataRow->setAttribute('summ', $row['summ']);
        }

        $xsl = dirname(__FILE__) . '/templates/queries_by_engine_more.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}


class LoggerModuleSourcesEnginesByQueryReport extends LoggerModuleSourcesSearchReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        if (!is_array($params) || !isset($params['text']) || !$params['text'])
            return false;

        $text = intval($params['text']);
        $textStr = '';
        $SelectSQL = 'SELECT `string` FROM `[PREF]module_sources_strings` WHERE `id`='.$text;
        $result = $this->database->Query($SelectSQL);
        if ($result && $row = $this->database->FetchAssoc($result))
            $textStr = $row['string'];
        $this->database->FreeResult($result);

        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'Поисковики по запросу ' . $textStr);
        $root->appendChild($name);

        $data = $this->GetEnginesByQueryData($date1, $date2, $text);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);
        $reportData->setAttribute('textId', $text);

        foreach($data as $row)
        {
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('engine', $row['engine']);
            $dataRow->setAttribute('page', $row['page']);
            $dataRow->setAttribute('summ', $row['summ']);
        }

        $xsl = dirname(__FILE__) . '/templates/engines_by_query.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}